import 'dart:async';

import 'package:enjoy_plus_hm/utils/event_bus.dart';
import 'package:enjoy_plus_hm/utils/http.dart';
import 'package:enjoy_plus_hm/utils/toast.dart';
import 'package:enjoy_plus_hm/utils/token.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController _phoneController = TextEditingController(
    text: '13800138000',
  );
  final TextEditingController _codeController = TextEditingController();

  int _countDown = 5; // 倒计时时长
  bool _isCountDown = false; // 倒计时状态
  Timer? _timer; // 定时器

  // 开始倒计时
  void _startCountDown() {
    if (_isCountDown) {
      return;
    }
    _isCountDown = true;
    setState(() {
      _countDown = 5;
    });
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        if (_countDown > 1) {
          _countDown--;
        } else {
          _isCountDown = false;
          _countDown = 5;
          timer.cancel();
        }
      });
    });
  }

  // 校验手机号
  void _checkPhone(String phone) {
    if (phone.isEmpty) {
      ToastUtil.showError('请输入手机号');
      throw Exception('请输入手机号');
    }
    RegExp reg = RegExp(r'^1[3456789]\d{9}$');
    if (!reg.hasMatch(phone)) {
      ToastUtil.showError('请输入正确的手机号');
      throw Exception('请输入正确的手机号');
    }
  }

  // 校验验证码
  void _checkCode(String code) {
    if (code.isEmpty) {
      ToastUtil.showError('请输入验证码');
      throw Exception('请输入验证码');
    }
    RegExp reg = RegExp(r'^\d{6}$');
    if (!reg.hasMatch(code)) {
      ToastUtil.showError('请输入正确的验证码');
      throw Exception('请输入正确的验证码');
    }
  }

  // 获取验证码
  void _getCode() async {
    try {
      // 1.校验手机号
      String phone = _phoneController.text;
      _checkPhone(phone);
      // 2.开始倒计时
      _startCountDown();
      // 3.发送请求获取验证码
      final res = await http.get('/code', params: {'mobile': phone});
      // 4.提示
      res['code'] == 10000
          ? ToastUtil.showSuccess('验证码发送成功')
          : ToastUtil.showError('验证码发送失败');
      // 接口太快了 所以延迟一下
      Future.delayed(Duration(seconds: 1), () {
        setState(() {
          _codeController.text = res['data']['code']; // 验证码回显
        });
      });
    } catch (e) {
      print(e);
    }
  }

  // 登录
  void _login() async {
    // 1.校验手机号和验证码
    try {
      String phone = _phoneController.text;
      String code = _codeController.text;
      _checkPhone(phone);
      _checkCode(code);
      final res = await http.post(
        '/login',
        data: {'mobile': phone, 'code': code},
      );
      if (res['code'] == 10000) {
        ToastUtil.showSuccess('登录成功');
        await TokenManager().setToken(res['data']['token']);
        // _timer!.cancel();
        eventBus.fire(RefreshMine()); // 通知个人中心页面重新获取数据
        if (mounted) {
          Navigator.pop(context);
        }
      } else {
        ToastUtil.showError(res['message']);
      }
    } catch (e) {
      throw Exception('登录失败：$e');
    }
  }

  @override
  void dispose() {
    _phoneController.dispose();
    _codeController.dispose();
    _timer?.cancel();
    super.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
                ),
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [Text('加入享+, 让生活更轻松', style: TextStyle(fontSize: 15))],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: _phoneController,
                    keyboardType: TextInputType.phone,
                    maxLength: 11,
                    style: TextStyle(fontSize: 16),
                    decoration: InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed:
                      _isCountDown
                          ? null
                          : () {
                            _getCode();
                          },
                  child:
                      _isCountDown
                          ? Text(
                            '$_countDown秒后重试',
                            style: TextStyle(color: Colors.grey),
                          )
                          : Text('获取验证码'),
                ),
              ],
            ),
            const SizedBox(height: 8),
            TextField(
              controller: _codeController,
              keyboardType: TextInputType.number,
              maxLength: 6,
              style: TextStyle(fontSize: 16),
              decoration: InputDecoration(
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      _login();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(color: Colors.white, fontSize: 20),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
